<?php

namespace app\beautiful\controller\admin\goods\menu\Foods;

use app\BaseController;
use app\beautiful\model\mall\GoodsModel;
use app\common\logic\DataLogic;
use think\facade\Db;


class Foods extends BaseController{

    protected $name='菜品';

    /**
     *菜单管理根据分类获取商品或套餐列表
     */
    public function index(){
        $category_id = $this->request->param('category_id/d',0);
        $search = $this->request->param('search');
        $where = [
            ['is_delete','=',0],
            ['shop_id','=',$this->request->shopId],
            ['type','=',1],
            ['category_id','=',$category_id]
        ];

        if($search){
            $where[]=['name','like','%'.$search.'%'];
        }
        $goodsModel = new GoodsModel;
        $goodsModel = $goodsModel->with(['categoty'=>function($query){
            $query->field('category_id,name')
                ->where(['shop_id'=>$this->request->shopId,'is_delete'=>0]);
        }]);
        $order = ['goods_id'=>'desc'];
        $field = "*";
        $append=['add_time_format'];

        $return = DataLogic::getDataList($goodsModel,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        return $this->success($return);
    }

    public function show()

    {

        $category = $this->getCategoryTreeData(0);

        $goods_id = $this->request->param('goods_id/d',0);

        if($goods_id==0) return $this->success(['category'=>$category]);

        $goods = GoodsModel::with(['unit'=>function($query){
            $query->field('other_sku_detail_id,group_detail_name')
                ->where(['shop_id'=>$this->request->shopId,'is_delete'=>0]);
        }])->where(['goods_id'=>$goods_id,'is_delete'=>0,'shop_id'=>$this->request->shopId,'type'=>1])
            ->json(['discount_detail'],true)
            ->find();

        if(null === $goods) {

            return $this->error($this->name.'不存在');

        }
        //会员折扣
        $discount_detail = $goods->discount_detail;
        if($goods->is_vip_discount>0 && $discount_detail){

            foreach ($discount_detail as $k=>$v){

                $level = LevelModel::find($v['level_id']);
                $discount_detail[$k]['name']=$level->name;
            }

        }
        $goods->discount_detail = $discount_detail;
        $sku = [];
        if($goods->is_have_sku){

            $sku = GoodsSkuModel::with(['unit'=>function($query){
                    $query->field('other_sku_detail_id,group_detail_name')
                        ->where(['shop_id'=>$this->request->shopId,'is_delete'=>0]);
                }])->where(['goods_id'=>$goods_id,'is_delete'=>0,'shop_id'=>$this->request->shopId])
                    ->select()->toArray() ?? [];
        }

        $goods->sku = $sku;

        return $this->success(['category'=>$category,'detail'=>$goods]);

    }

    public function save()

    {

        $goods_id = $this->request->param('goods_id/d',0);

        $name = $this->request->param('name');

        $type = $this->request->param('type');

        $category_id = $this->request->param('category_id/d',0);

        $sort = $this->request->param('sort/d',0);

        $is_have_sku = $this->request->param('is_have_sku/d',0);

        $sku_name = $this->request->param('sku_name');

        $unit_id = $this->request->param('unit_id/d',0);

        $bar_code = $this->request->param('bar_code');

        $original_price = $this->request->param('original_price/f',0);

        $vip_price = $this->request->param('vip_price/f',0);

        $gross = $this->request->param('gross/f',0);

        $quota = $this->request->param('quota/d',0);

        $weight = $this->request->param('weight/f',0);

        $is_vip_discount = $this->request->param('is_vip_discount/d',0);

        $cover_img = $this->request->param('cover_img');

        $rotation = $this->request->param('rotation/a',[]);

        $goods_details = $this->request->param('goods_details','','security_json_or_array');

        $status = $this->request->param('status/d',-1);

        $discount_detail = $this->request->param('discount_detail');

        //$sku_detail = $this->request->param('sku_detail');

        //测试数据
        $discount_detail[]=[
            'level_id'=>7,
            'member_price'=>9
        ];
        $discount_detail[]=[
            'level_id'=>8,
            'member_price'=>8
        ];
        $discount_detail[]=[
            'level_id'=>9,
            'member_price'=>7
        ];
        $discount_detail[]=[
            'level_id'=>43,
            'member_price'=>6
        ];
        $discount_detail[]=[
            'level_id'=>47,
            'member_price'=>5
        ];

        $discount_detail1[]=[
            'level_id'=>7,
            'member_price'=>9.5
        ];
        $discount_detail1[]=[
            'level_id'=>8,
            'member_price'=>8.5
        ];
        $discount_detail1[]=[
            'level_id'=>9,
            'member_price'=>7.5
        ];
        $discount_detail1[]=[
            'level_id'=>43,
            'member_price'=>6.5
        ];
        $discount_detail1[]=[
            'level_id'=>47,
            'member_price'=>5.5
        ];


        $sku_detail[]=[
            // 'sku_id'=>151,
            'name'=>'矿泉水',
            'unit_id'=>9,
            'bar_code'=>'1000',
            'original_price'=>10,
            'gross'=>5,
            'quota'=>10,
            'weight'=>10,

        ];
//        $sku_detail[]=[
//           // 'sku_id'=>152,
//            'name'=>'60ml',
//            'unit_id'=>10,
//            'bar_code'=>'1001',
//            'original_price'=>18,
//            'gross'=>10,
//            'quota'=>10,
//            'weight'=>20,
//        ];


        //判断传来的参数

        if(empty($name)) return $this->error('请输入名称');


        if(empty($category_id)) return $this->error('请选择分类');

        if(!in_array($is_vip_discount,[0,1,2,3])) return $this->error('未设置会员价类型');

        if(!$sku_detail) return $this->error('至少一个规格');


        if($is_have_sku && $sku_detail){

            $quota=0;

            foreach ($sku_detail as $k => $v){

                if(empty($v['name'])) return $this->error('请输入规格第'.($k+1).'行的名称');

                if(empty($v['unit_id'])) return $this->error('请选择规格第'.($k+1).'行的单位');

                if(empty($v['bar_code'])) return $this->error('请输入规格第'.($k+1).'行的条码');

                if(empty($v['original_price']) || $v['original_price'] <= 0) return $this->error('请输入规格第'.($k+1).'行的原价，且不能小于0');

                if(empty($v['quota']) || $v['quota'] <= 0) return $this->error('请输入规格第'.($k+1).'行的库存，且不能小于0');

                $quota=$quota+$v['quota'];

            }

        }

        if(empty($cover_img)) return $this->error('请上传缩略图');

        if(empty($rotation) || !is_array($rotation) || count($rotation)>5) return $this->error('请上传轮播图，且数量不能多余5个');

        if(empty($goods_details)) return $this->error('请填写商品详情');



        //保存操作

        if($goods_id != 0){

            if(null === $goods= GoodsModel::find($goods_id)) return $this->error($this->name.'不存在');

            //之前的商品不能修改
            if($goods->add_time){

            }
            if($goods->is_delete!=0) return $this->error($this->name.'不存在');

            if($goods->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

            $pre_cover_img=$goods->cover_img; $pre_rotation=$goods->rotation; $pre_goods_details=$goods->goods_details;

        }else{

            $goods = new GoodsModel();

            $goods->shop_id = $this->request->shopId;

            $pre_cover_img=null; $pre_rotation=[]; $pre_goods_details=[];

        }


        Db::startTrans();

        try{

            $goods->name = $name;

            $goods->type = $type;

            $goods->sku_name = $sku_name;

            $goods->unit_id = $unit_id;

            $goods->bar_code = $bar_code;

            $goods->original_price = $original_price;

            $goods->vip_price = $vip_price;

            $goods->gross = $gross;

            $goods->quota = $quota;

            $goods->weight = $weight;

            $goods->category_id = $category_id;

            $goods->sort = $sort;

            $goods->is_vip_discount = $is_vip_discount;

            $goods->cover_img = $cover_img;

            $goods->rotation = $rotation;

            $goods->goods_details = $goods_details;

            $goods->update_time = $this->request->time();

            $goods->status = $status;

            $goods->is_have_sku = $is_have_sku;

            $goods->discount_detail = json_encode($discount_detail,true);

            $goods->save();


            //GoodsModel::where(['goods_id'=>$goods->goods_id,'shop_id'=>$this->request->shopId])->json(['discount_detail'],true)->update(['discount_detail'=>$discount_detail]);

            //规格操作
            if($goods->is_have_sku<1){
                GoodsSkuModel::where([

                    ['shop_id','=',$this->request->shopId],

                    ['goods_id','=',$goods->goods_id],

                    ['is_delete','=',0]

                ])->save(['is_delete'=>1]);
            }

            if($sku_detail && $goods->is_have_sku){

                $old_sku=GoodsSkuModel::where([

                    ['shop_id','=',$this->request->shopId],

                    ['goods_id','=',$goods->goods_id],

                    ['is_delete','=',0]

                ])->json(['discount_detail'],true)->select()->toArray();


                $update_goods_ids=array_column($sku_detail,'sku_id') ?? []; $delete_goods_sku=[];

                $old_sku_ids=array_column($old_sku,'sku_id') ?? [];

                foreach ($old_sku as $k => $v){

                    if(!in_array($v['sku_id'],$update_goods_ids)){

                        $v['is_delete']=1;

                        $delete_goods_sku[]=$v;

                    }

                }

                foreach ($sku_detail as $k => $v){

                    $sku_detail[$k]['shop_id']=$this->request->shopId;

                    $sku_detail[$k]['goods_id']=$goods->goods_id;

                    if(isset($v['sku_id'])){

                        if(!in_array($v['sku_id'],$old_sku_ids)) unset($sku_detail[$k]);

                    }

                }

                $new_sku=array_merge($sku_detail,$delete_goods_sku);
                //删除

                $goods_sku_model= new GoodsSkuModel();

                $goods_sku_model->saveAll($new_sku);


            }

            Db::commit();
        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

        //图片操作

        imgReplaceAct($cover_img,$pre_cover_img);

        arrayNoUseImg($pre_rotation); arrayUseImg($rotation);

        arrayNoUseImg($pre_goods_details); arrayUseImg($goods_details);

        return $this->success('操作成功');

    }

    protected function getCategoryTreeData($pid=0)

    {

        $return=[];

        $category= GoodsCategoryModel::where([

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

            ['pid','=',$pid]

        ])->select()->toArray();

        if(!empty($category)){

            foreach ($category as $k => $v){

                $return[$k]=[

                    'title'=>$v['name'],

                    'value'=>$v['category_id'],

                    'key'=>$v['category_id'],

                    'children'=> $this->getCategoryTreeData($v['category_id']),

                ];

            }

        }

        return $return;

    }
    /**
     *上架/下架
     */
    public function saveStatus()

    {

        $goods_id = $this->request->param('goods_id/d',0);
        $status = $this->request->param('status');

        if(!in_array($status,[1,-1]))  return $this->error('状态有误');

        if(null === $goods= GoodsModel::find($goods_id)) return $this->error('不存在');
        if($goods->is_delete!=0) return $this->error('不存在');
        if($goods->shop_id != $this->request->shopId) return $this->error('不存在');

        //其他判断后面补充
//        if($goods->type == 1){
//            //判断有没有套餐关联了该产品
//            $goods = GoodsGroupDetailModel::where(['goods_id'=>$goods_id,'is_delete'=>0,'shop_id'=>$this->request->shopId])->select()->toArray()??[];
//            if($goods){
//                return $this->error('该产品已被套餐关联，需要删除关联的产品，才能下架');
//            }
//            //判断有没有会员折扣关联该产品
//            $level_benefits = LevelBenefitsModel::where(['goods_id'=>$goods_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find;
//            if($level_benefits){
//                return $this->error('该产品已被会员折扣关联，需要删除关联的产品，才能下架');
//            }
//        }


        $goods->status = $status;
        $goods->save();

        return $this->success('操作成功');

    }
    /**
     *删除
     */
    public function del()

    {

        $goods_id = $this->request->param('goods_id');


        //其他判断后面补充

        GoodsModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'type'=>1])->whereIn('goods_id',$goods_id)->update(['is_delete'=>1]);

        return $this->success('操作成功');
    }

    /**
     * 删除菜品的分类
     */
    public function delCategoty(){
        $goods_id = $this->request->param('goods_id');
        $category_id = $this->request->param('category_id');

        $goods = GoodsModel::where(['goods_id'=>$goods_id,'is_delete'=>0,'shop_id'=>$this->request->shopId])->find();
        if(null === $goods) return $this->error($this->name.'不存在');

        $category_ids_arr = explode(',',$goods->category_id);
        $key = array_search($category_id,$category_ids_arr,true);
        if($key!==false){
            unset($category_ids_arr[$key]);
        }
        $goods->category_id = implode(',',$category_ids_arr);
        $goods->save();
        return $this->success('操作成功');
    }

}

